package com.arui.security;

import com.arui.domain.AruioRole;
import com.arui.domain.AruioUser;
import com.arui.service.AruioRoleService;
import com.arui.service.AruioUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Date 2024/8/23 9:56
 * @Created by 10574
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {
    private final AruioUserService aruioUserService;
    private final AruioRoleService aruioRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final AruioUser aruioUser = aruioUserService.getUserByName(username);
        if (Objects.isNull(aruioUser) || Objects.isNull(aruioUser.getId())) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        log.info("---------用户:{}, 查询权限---------", username);
        final List<GrantedAuthority> authorities = new ArrayList<>();

        // 根据用户获取角色
        final List<String> roleList = aruioRoleService.findRoleListByUserId(aruioUser.getId())
                .stream()
                .map(AruioRole::getName)
                .collect(Collectors.toList());
        log.info("---------用户:{}, 权限如下:{}---------", username, Arrays.toString(roleList.toArray()));
        return new AruioUserDetail(aruioUser, roleList);
    }
}
